﻿#include<iostream>
#include<fstream>
#include<conio.h>
#include<Windows.h>
#include<tchar.h>
using namespace std;

int IFNUM=0;	//旗帜
string FNTBEN;//待加密文件名
string ENFN;//加密文件名
string WDEFN;//待解密文件名
string DEFN;//解密文件名
fstream fnt, enf;//fnt待输入文件流，enf待输出文件流

const string JMS = "加密中···";
const string JMZ = "解密中···";

//文件加
int Encrypt()
{
	cout << "请输入加密文件路径及名称：" << endl;
	cin >> FNTBEN;
	ENFN = "加密" + FNTBEN;
	cout << "加密后文件名为：" << ENFN << endl;

	fnt.open(FNTBEN, std::ios::in | std::ios::binary);	//打开输入文件流（以二进制方式）
	enf.open(ENFN, std::ios::out | std::ios::binary);	//打开输出文件流（以二进制方式）

	fnt.seekg(0, ios::end);	//第一个参数：文件偏移字节数；第二个参数：文件位置
	std::streamoff size = fnt.tellg();	//待处理文件总长度
	fnt.seekg(0, ios::beg);	//ios::beg文件开头，ios::cur文件当前位置，ios::end文件末尾
	printf("文件大小为%lld字节\n", size);
	for (int i = 0; i < size; i++)
	{
		enf.put(fnt.get() ^ 0x86);	//将读入的二级制字符进行位运算
	}

	//关闭文件
	fnt.close();
	enf.close();
	return 0;
}

//文件解密
int Decrypt()
{
	cout << "请输入待解密文件路径及名称：" << endl;
	cin >> WDEFN;
	DEFN = "解密" + WDEFN;
	cout << "解密后文件名为：" << DEFN << endl;

	fnt.open(WDEFN, std::ios::in | std::ios::binary);
	enf.open(DEFN, std::ios::out | std::ios::binary);

	fnt.seekg(0, ios::end);
	std::streamoff size = fnt.tellg();
	fnt.seekg(0, ios::beg);
	printf("文件大小为%lld字节\n", size);

	for (int i = 0; i < size; i++)
	{
		enf.put(fnt.get() ^ 0x86);
	}

	fnt.close();
	enf.close();
	return 0;
}

int show()
{
	HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTitle(_T("文档加密解密"));
	cout << "██████"<<endl;
	cout << "文档加密解密" << endl;
	cout << "1.加密" << endl;
	cout << "2.解密" << endl;
	cout << "3.退出" << endl;
	cout << "██████" << endl;
	return 0;
}

int main()
{
	while (TRUE)
	{
		show();
		cin >> IFNUM;
		if (cin.fail())
		{
			cout << "错误" <<"\a"<< endl;
			cin.clear();
			//cin.sync();
			while (cin.get() != '\n');
			//cin.ignore(1, EOF);
			//cin.ignore(1i64, '\n');
		}
		else
		{
			switch (IFNUM)
			{
			case 1:
				Encrypt();
				cout << JMS << endl;
				Sleep(100);
				cout << "加密完成！" << endl;
				break;
			case 2:
				Decrypt();
				cout << JMZ << endl;
				Sleep(100);
				cout << "解密完成！" << endl;
				break;
			case 3:
				exit(0);
				break;
			}
		}
	}
	return 0;
}